<?php

/************************************************************
 * 文章系统处理工具
 * time		2014-08-20
 * author	liuricheng
 * 
 ***********************************************************/

/**
 * 获取商品类型中包含规格的类型列表
 *
 * @access  public
 * @return  array
 */
function get_goods_type_specifications(){
   
    $sql 		= 	"SELECT DISTINCT cat_id
            		FROM " . 'ybr_attribute' . "
            		WHERE attr_type = 1";
    $row 		= 	M()->query($sql);

    $return_arr = array();
    if (!empty($row)){
        foreach ($row as $value){
            $return_arr[$value['cat_id']] 	= 	$value['cat_id'];
        }
    }
    return $return_arr;
}

/**
 * 获得商品已添加的规格列表
 *
 * @access      public
 * @params      integer         $goods_id
 * @return      array
 */
function get_goods_specifications_list($goods_id){
    if (empty($goods_id)){
        return array();  //$goods_id不能为空
    }

    $sql 	= 	"SELECT g.goods_attr_id, g.attr_value, g.attr_id, a.attr_name
            	FROM " . 'ybr_goods_attr' . " AS g
                LEFT JOIN " . 'ybr_attribute' . " AS a
                  ON a.attr_id = g.attr_id
            	WHERE goods_id = '$goods_id'
            	AND a.attr_type = 1
            	ORDER BY g.attr_id ASC";
    $results =	M()->query($sql);
    return $results;
}

/**
 * 获得指定商品相关的商品
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_linked_goods($goods_id)
{
    $sql 	= 	"SELECT lg.link_goods_id AS goods_id, g.goods_name, lg.is_double " .
            	"FROM " . 'ybr_link_goods' . " AS lg, " .
                'ybr_goods' . " AS g " .
            	"WHERE lg.goods_id = '$goods_id' " .
            	"AND lg.link_goods_id = g.goods_id ";
    if ($goods_id == 0){
        $sql 	.= 	" AND lg.admin_id = '$_SESSION[admin_id]'";
    }
    $row 	= 	M()->query($sql);

    foreach ($row AS $key => $val){
        $linked_type 				= 	$val['is_double'] == 0 ? $GLOBALS['_LANG']['single'] : $GLOBALS['_LANG']['double'];
        $row[$key]['goods_name'] 	= 	$val['goods_name'] . " -- [$linked_type]";
        unset($row[$key]['is_double']);
    }
    return $row;
}

/**
 * 获得指定商品的配件
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_group_goods($goods_id)
{
    $sql 	= 	"SELECT gg.goods_id, CONCAT(g.goods_name, ' -- [', gg.goods_price, ']') AS goods_name " .
            	"FROM " . 'ybr_group_goods' . " AS gg, " .
                'ybr_goods' . " AS g " .
            	"WHERE gg.parent_id = '$goods_id' " .
            	"AND gg.goods_id = g.goods_id ";
    if ($goods_id == 0){
        $sql 	.= 	" AND gg.admin_id = '$_SESSION[admin_id]'";
    }
    $row 		= 	M()->query($sql);
    return $row;
}

/**
 * 获得商品的关联文章
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_goods_articles($goods_id)
{
    $sql 	= 	"SELECT g.article_id, a.title " .
            	"FROM " . ' ybr_goods_article ' . " AS g, " .
                ' ybr_article ' . " AS a " .
            	"WHERE g.goods_id = '$goods_id' " .
            	"AND g.article_id = a.article_id ";
    if ($goods_id == 0){
        $sql 	.= 	" AND g.admin_id = '$_SESSION[admin_id]'";
    }
    
    $row 	= 	M()->query($sql);
    return $row;
}

/**
 * 取得品牌列表
 * @return array 品牌列表 id => name
 */
function get_brand_list()
{
    $sql 	= 	'SELECT brand_id, brand_name FROM ' . 'ybr_brand' . ' ORDER BY sort_order';
    $res 	= 	M()->query($sql);

    $brand_list 	= 	array();
    foreach ($res AS $row){
        $brand_list[$row['brand_id']] 	= 	addslashes($row['brand_name']);
    }
    return $brand_list;
}

/**
 * 取得重量单位列表
 * @return  array   重量单位列表
 */
function get_unit_list()
{
    return array(
        '1'     =>'千克',
        '0.001' =>'克',
    );
}

/**
 * 取得会员等级列表
 * @return  array   会员等级列表
 */
function get_user_rank_list()
{
    $sql 	= 	"SELECT * FROM " .' ybr_user_rank ' .
           		" ORDER BY min_points";
    return M()->query($sql);
}

/**
 * 取得某商品的会员价格列表
 * @param   int     $goods_id   商品编号
 * @return  array   会员价格列表 user_rank => user_price
 */
function get_member_price_list($goods_id){
    /* 取得会员价格 */
    $price_list 	= 	array();
    $sql 			= 	"SELECT user_rank, user_price FROM " .
			            ' ybr_member_price' .
			            " WHERE goods_id = '$goods_id'";
    $res 			= 	M()->query($sql);
    foreach($res as $row){
    	$price_list[$row['user_rank']] = $row['user_price'];
    }
    return $price_list;
}

/**
 * 获得商品类型的列表
 *
 * @access  public
 * @param   integer     $selected   选定的类型编号
 * @return  string
 */
function goods_type_list($selected)
{
    $sql 	= 	'SELECT cat_id, cat_name FROM ' . 'ybr_goods_type' . ' WHERE enabled = 1';
    $res 	= 	M()->query($sql);
	
    $list 	= 	'';
    foreach($res as $row){
    	$list .= "<option value='$row[cat_id]'";
        $list .= ($selected == $row['cat_id']) ? ' selected="true"' : '';
        $list .= '>' . htmlspecialchars($row['cat_name']). '</option>';
    }
    return $list;
}


/**
 * 取得商品优惠价格列表
 *
 * @param   string  $goods_id    商品编号
 * @param   string  $price_type  价格类别(0为全店优惠比率，1为商品优惠价格，2为分类优惠比率)
 *
 * @return  优惠价格列表
 */
function get_volume_price_list($goods_id, $price_type = '1')
{
    $volume_price = array();
    $temp_index   = '0';

    $sql 	= 	"SELECT `volume_number` , `volume_price`".
           		" FROM " . 'ybr_volume_price' . "".
           		" WHERE `goods_id` = '" . $goods_id . "' AND `price_type` = '" . $price_type . "'".
           		" ORDER BY `volume_number`";

    $res 	= 	M()->query($sql);

    foreach ($res as $k => $v){
        $volume_price[$temp_index]                 = array();
        $volume_price[$temp_index]['number']       = $v['volume_number'];
        $volume_price[$temp_index]['price']        = $v['volume_price'];
        $volume_price[$temp_index]['format_price'] = price_format($v['volume_price']);
        $temp_index ++;
    }
    return $volume_price;
}

/**
 * 根据属性数组创建属性的表单
 *
 * @access  public
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  string
 */
function build_attr_html($cat_id, $goods_id = 0)
{
    $attr = get_attr_list($cat_id, $goods_id);    
    $html = '<table width="100%" id="attrTable">';
    $spec = 0;
    foreach ($attr AS $key => $val)
    {
        $html .= "<tr><td class='label'>";
        if ($val['attr_type'] == 1 || $val['attr_type'] == 2)
        {
            $html .= ($spec != $val['attr_id']) ?
                "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" :
                "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
            $spec = $val['attr_id'];
        }

        $html .= "$val[attr_name]</td><td><input type='hidden' name='attr_id_list[]' value='$val[attr_id]' />";

        if ($val['attr_input_type'] == 0)
        {
            $html .= '<input name="attr_value_list[]" type="text" value="' .htmlspecialchars($val['attr_value']). '" size="40" /> ';
        }
        elseif ($val['attr_input_type'] == 2)
        {
            $html .= '<textarea name="attr_value_list[]" rows="3" cols="40">' .htmlspecialchars($val['attr_value']). '</textarea>';
        }
        else
        {
            $html .= '<select name="attr_value_list[]">';
            $html .= '<option value="">' . '请选择' . '</option>';

            $attr_values = explode("\n", $val['attr_values']);

            foreach ($attr_values AS $opt)
            {
                $opt    = trim(htmlspecialchars($opt));

                $html   .= ($val['attr_value'] != $opt) ?
                    '<option value="' . $opt . '">' . $opt . '</option>' :
                    '<option value="' . $opt . '" selected="selected">' . $opt . '</option>';
            }
            $html .= '</select> ';
        }

        $html .= 	($val['attr_type'] == 1 || $val['attr_type'] == 2) ? 
        			$GLOBALS['_LANG']['spec_price'].' <input type="text" name="attr_price_list[]" value="' . $val['attr_price'] . '" size="5" maxlength="10" />' :
            		' <input type="hidden" name="attr_price_list[]" value="0" />';

        $html .= '</td></tr>';
    }

    $html .= '</table>';
	    
    return $html;
}

/**
 * 取得通用属性和某分类的属性，以及某商品的属性值
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  array   规格与属性列表
 */
function get_attr_list($cat_id, $goods_id = 0){
    if (empty($cat_id)){
        return array();
    }
    // 查询属性值及商品的属性值
    $sql 	= 	"SELECT a.attr_id, a.attr_name, a.attr_input_type, a.attr_type, a.attr_values, v.attr_value, v.attr_price ".
	            "FROM " .  'ybr_attribute' . " AS a ".
	            "LEFT JOIN " . 'ybr_goods_attr' . " AS v ".
	            "ON v.attr_id = a.attr_id AND v.goods_id = '$goods_id' ".
	            "WHERE a.cat_id = " . intval($cat_id) ." OR a.cat_id = 0 ".
	            "ORDER BY a.sort_order, a.attr_type, a.attr_id, v.attr_price, v.goods_attr_id";
    $row = M()->query($sql);
    return $row;
}




/**
 * 保存某商品的会员价格
 * @param   int     $goods_id   商品编号
 * @param   array   $rank_list  等级列表
 * @param   array   $price_list 价格列表
 * @return  void
 */
function handle_member_price($goods_id, $rank_list, $price_list)
{
	$CommonModel	=	new CommonModel();
    /* 循环处理每个会员等级 */
    foreach ($rank_list AS $key => $rank)
    {
        /* 会员等级对应的价格 */
        $price 		= 	$price_list[$key];

        // 插入或更新记录
        $sql 		= 	"SELECT COUNT(*) FROM " . ' ybr_member_price' .
               			" WHERE goods_id = '$goods_id' AND user_rank = '$rank'";
        if ($CommonModel->getOne($sql) > 0)
        {
            /* 如果会员价格是小于0则删除原来价格，不是则更新为新的价格 */
            if ($price < 0)
            {
                $sql 	= 	"DELETE FROM " . ' ybr_member_price ' .
                       		" WHERE goods_id = '$goods_id' AND user_rank = '$rank' LIMIT 1";
            }
            else
            {
                $sql 	= 	"UPDATE " . ' ybr_member_price ' .
                       		" SET user_price = '$price' " .
                       		"WHERE goods_id = '$goods_id' " .
                       		"AND user_rank = '$rank' LIMIT 1";
            }
        }
        else
        {
            if ($price == -1)
            {
                $sql = '';
            }
            else
            {
                $sql 	= 	"INSERT INTO " . ' ybr_member_price ' . " (goods_id, user_rank, user_price) " .
                       		"VALUES ('$goods_id', '$rank', '$price')";
            }
        }

        if ($sql)
        {
            M()->query($sql);
        }
    }
}

/**
 * 保存某商品的优惠价格
 * @param   int     $goods_id    商品编号
 * @param   array   $number_list 优惠数量列表
 * @param   array   $price_list  价格列表
 * @return  void
 */
function handle_volume_price($goods_id, $number_list, $price_list)
{
    $sql 		= 	"DELETE FROM " . ' ybr_volume_price ' .
           			" WHERE price_type = '1' AND goods_id = '$goods_id'";
    M()->query($sql);

    /* 循环处理每个优惠价格 */
    foreach ($price_list AS $key => $price)
    {
        /* 价格对应的数量上下限 */
        $volume_number 	= 	$number_list[$key];

        if (!empty($price))
        {
            $sql 	= 	"INSERT INTO " . ' ybr_volume_price' .
                   		" (price_type, goods_id, volume_number, volume_price) " .
                   		"VALUES ('1', '$goods_id', '$volume_number', '$price')";
            M()->query($sql);
        }
    }
}


/**
 * 保存某商品的扩展分类
 * @param   int     $goods_id   商品编号
 * @param   array   $cat_list   分类编号数组
 * @return  void
 */
function handle_other_cat($goods_id, $cat_list)
{
    /* 查询现有的扩展分类 */
    $sql 		= 	"SELECT cat_id FROM " . ' ybr_goods_cat' .
            		" WHERE goods_id = '$goods_id'";
    $exist_list = 	M()->getCol($sql);

    /* 删除不再有的分类 */
    $delete_list = array_diff($exist_list, $cat_list);
    if ($delete_list)
    {
        $sql 	= 	"DELETE FROM " . ' ybr_goods_cat' .
                	" WHERE goods_id = '$goods_id' " .
                	"AND cat_id " . db_create_in($delete_list);
        M()->query($sql);
    }

    /* 添加新加的分类 */
    $add_list 	= 	array_diff($cat_list, $exist_list, array(0));
    foreach ($add_list AS $cat_id)
    {
        // 插入记录
        $sql 	= 	"INSERT INTO " . ' ybr_goods_cat' .
                	" (goods_id, cat_id) " .
                	"VALUES ('$goods_id', '$cat_id')";
        M()->query($sql);
    }
}

/**
 * 保存某商品的关联商品
 * @param   int     $goods_id
 * @return  void
 */
function handle_link_goods($goods_id)
{
    $sql = "UPDATE " . ' ybr_link_goods ' . " SET " .
            " goods_id = '$goods_id' " .
            " WHERE goods_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    M()->query($sql);

    $sql = "UPDATE " . ' ybr_link_goods ' . " SET " .
            " link_goods_id = '$goods_id' " .
            " WHERE link_goods_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    M()->query($sql);
}

/**
 * 保存某商品的配件
 * @param   int     $goods_id
 * @return  void
 */
function handle_group_goods($goods_id)
{
    $sql = "UPDATE " . ' ybr_group_goods ' . " SET " .
            " parent_id = '$goods_id' " .
            " WHERE parent_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    M()->query($sql);
}

/**
 * 保存某商品的关联文章
 * @param   int     $goods_id
 * @return  void
 */
function handle_goods_article($goods_id)
{
    $sql = "UPDATE " . ' ybr_goods_article ' . " SET " .
            " goods_id = '$goods_id' " .
            " WHERE goods_id = '0'" .
            " AND admin_id = '$_SESSION[admin_id]'";
    M()->query($sql);
}


